<?php

namespace Admin\Controller;

use Admin\Controller\CommonController;
use Usap\Service\Service;

/**
 * 后台用户相关模块
 */
class AdminController extends CommonController
{


    /**
     * 修改个人信息
     */
    public function public_editInfo($info = array())
    {
        $userid = session('userid');
        $admin_db = D('Usap/Admin/Admin');;
        if (IS_POST) {
            $fields = array('email', 'realname');
            foreach ($info as $k => $value) {
                if (!in_array($k, $fields)) {
                    unset($info[$k]);
                }
            }
            $state = $admin_db->where(array('userid' => $userid))->save($info);
            $state ? $this->success('修改成功') : $this->error('修改失败');
        } else {
            $menu_db = D('Usap/Admin/Menu');
            $currentpos = $menu_db->currentPos(I('get.menuid'));  //栏目位置
            $info = $admin_db->where(array('userid' => $userid))->find();

            $this->assign('info', $info);
            $this->assign('currentpos', $currentpos);
            $this->display('edit_info');
        }
    }

    /**
     * 修改密码
     */
    public function public_editPwd()
    {
        $userid = session('userid');
        $admin_db = D('Usap/Admin/Admin');
        if (IS_POST) {

            $old_password = I('post.old_password');
            if (empty($old_password)) {
                $this->error('请输入原密码');
            }

            $new_password = I('post.new_password');
            if (empty($new_password)) {
                $this->error('请输入新密码');
            }

            if (I('post.new_password')) {

                $is_modified = 1;
                $state = $admin_db->editPassword($userid, I('post.old_password'), I('post.new_password'), $is_modified);

                if (!$state) $this->error($admin_db->error);
            }
            session('userid', null);
            session('roleid', null);
            cookie('username', null);
            cookie('userid', null);
            $this->success('密码修改该成功,请使用新密码重新登录', U('admin/Index/logout'));
        } else {
            $menu_db = D('Usap/Admin/Menu');
            $currentpos = $menu_db->currentPos(I('get.menuid'));  //栏目位置
            $info = $admin_db->where(array('userid' => $userid))->find();

            $this->assign('info', $info);
            $this->assign(currentpos, $currentpos);
            $this->display('edit_password');
        }
    }

    /**
     * 登录日志
     */
    public function loginLog($page = 1, $rows = 10, $search = array(), $sort = 'time', $order = 'desc')
    {
        if (IS_POST) {
            $userid = session('userid');

            $admin_log = D('Usap/Admin/AdminLog');
            //搜索
            $where = array("`type` = 'login'", "`userid` = {$userid}");
            foreach ($search as $k => $v) {
                if (!$v) continue;
                switch ($k) {
                    case 'begin':
                        if (!preg_match("/^\d{4}(-\d{2}){2}$/", $v)) {
                            unset($search[$k]);
                            continue;
                        }
                        if ($search['end'] && $search['end'] < $v) $v = $search['end'];
                        $where[] = "`time` >= '{$v}'";
                        break;
                    case 'end':
                        if (!preg_match("/^\d{4}(-\d{2}){2}$/", $v)) {
                            unset($search[$k]);
                            continue;
                        }
                        if ($search['begin'] && $search['begin'] > $v) $v = $search['begin'];
                        $where[] = "`time` <= '{$v}'";
                        break;
                }
            }
            $where = implode(' and ', $where);

            $limit = ($page - 1) * $rows . "," . $rows;
            $order = $sort . ' ' . $order;
            $total = $admin_log->where($where)->count();
            $list = $total ? $admin_log->where($where)->order($order)->limit($limit)->select() : array();

            $data = array('total' => $total, 'rows' => $list);
            $this->ajaxReturn($data);
        } else {
            $menu_db = D('Usap/Admin/Menu');
            $currentpos = $menu_db->currentPos(I('get.menuid'));  //栏目位置


            $datagrid = array(
                'options' => array(
                    'title' => $currentpos,
                    'url' => U('admin/Admin/loginLog', array('grid' => 'datagrid')),
                    'toolbar' => '#admin-loginlog-datagrid-toolbar',
                ),
                'fields' => array(
                    '用户名' => array('field' => 'username', 'width' => 20),
                    '登录时间' => array('field' => 'time', 'width' => 30, 'sortable' => true),
                    '浏览器标识' => array('field' => 'httpuseragent', 'width' => 100),
                    'IP' => array('field' => 'ip', 'width' => 25, 'sortable' => true),
                )
            );
            $this->assign('datagrid', $datagrid);
            $this->display('login_log');
        }
    }

    /**
     * 删除登录日志
     */
    public function loginLogDelete($week = 4)
    {
        $userid = session('userid');
        $admin_log = D('Usap/Admin/AdminLog');
        $start = time() - $week * 7 * 24 * 3600;
        $d = date('Y-m-d', $start);
        $where = "`type` = 'login' AND `userid` = {$userid} AND left(`time`, 10) <= '$d'";
        $result = $admin_log->where($where)->delete();
        $result ? $this->success('删除成功') : $this->error('没有数据或已删除过了，请稍后再试');
    }

    /**
     * 用户管理
     */
    public function memberList($page = 1, $rows = 10, $sort = 'userid', $order = 'desc')
    {
        if (IS_POST) {
            $admin_db = D('Usap/Admin/Admin');
            $admin_role_db = D('Usap/Admin/Role');
            $rolelist = $admin_role_db->where(array('disabled' => '0'))->order('listorder asc')->getField('roleid,rolename', true);

            $total = $admin_db->count();
            $order = $sort . ' ' . $order;
            $limit = ($page - 1) * $rows . "," . $rows;
            $list = $total ? $admin_db->field('userid,username,lastloginip,email,realname,lastlogintime,roleid,relationuid,mobile')->order($order)->limit($limit)->select() : array();
            foreach ($list as &$info) {
                $info['rolename'] = isset($rolelist[$info['roleid']]) ? $rolelist[$info['roleid']] : '-';
                $info['lastlogintime'] = $info['lastlogintime'] ? date('Y-m-d H:i:s', $info['lastlogintime']) : '-';
                $info['relationuid'] = empty($info['relationuid']) ? '-1' : $info['relationuid'];
                if (empty($info['mobile'])) {
                    $info['mobile'] = '';
                } else {
                    $info['mobile'] = substr($info['mobile'], 0, 3) . '*****' . substr($info['mobile'], -3);
                }
            }
            $data = array('total' => $total, 'rows' => $list);
            $this->ajaxReturn($data);
        } else {
            $menu_db = D('Usap/Admin/Menu');
            $currentpos = $menu_db->currentPos(I('get.menuid'));  //栏目位置
            $datagrid = array(
                'options' => array(
                    'title' => $currentpos,
                    'url' => U('admin/Admin/memberList', array('grid' => 'datagrid')),
                    'toolbar' => 'adminMemberModule.toolbar',
                ),
                'fields' => array(
                    '用户名' => array('field' => 'username', 'width' => 20, 'sortable' => true),
                    '所属角色' => array('field' => 'rolename', 'width' => 20),
// 					'E-mail'     => array('field'=>'email','width'=>25,'sortable'=>true),
                    '手机号' => array('field' => 'mobile', 'width' => 25, 'sortable' => true),
                    '真实姓名' => array('field' => 'realname', 'width' => 25, 'sortable' => true),
                    '最后登录IP' => array('field' => 'lastloginip', 'width' => 25, 'sortable' => true),
                    '最后登录时间' => array('field' => 'lastlogintime', 'width' => 30, 'sortable' => true, 'formatter' => 'adminMemberModule.time'),
                    '管理操作' => array('field' => 'userid', 'width' => 40, 'formatter' => 'adminMemberModule.operate'),
                )
            );
            $this->assign('datagrid', $datagrid);
            $this->display('member_list');
        }
    }

    /**
     * 添加用户
     */
    public function memberAdd()
    {
        if (IS_POST) {
            $user_service = Service::instance()->find('account', 'user');
            $admin_db = D('Usap/Admin/Admin');
            $user_db = D("Usap/Account/user");
            $data = I('post.info');
            if ($admin_db->where(array('username' => $data['username']))->field('username')->find()) {
                $this->error('用户名称已经存在');
            }
            //除超级管理员外 所有用户都能登陆app
                //插入记录
                $timestamp = time();
                $password = $user_service->genPasswd(md5($data['password']), $timestamp);
                //添加唯一标识
                $union_id = substr(md5((uniqid(uniqid(), true))), 0, 10);
                $user_data = array(
                    'user_password' => $password,
                    'user_name' => $data['username'],
                    'status' => 'Active',
                    'realname' => $data['realname'],
                    'mobile' => $data['mobile'],
                    'reg_time' => date('Y-m-d H:i:s', $timestamp),
                    'terminal_id' => 0,//设备类型ID
                    'union_id' => $union_id,
                );
                //注册成功
                $id = $user_db->add($user_data);
                $data['relationuid'] = $id;
                $passwordinfo = password($data['password']);
                $data['password'] = $passwordinfo['password'];
                $data['encrypt'] = $passwordinfo['encrypt'];
                $admin_db->add($data);
            if ($id) {
                $this->success('添加成功');
            } else {
                $this->error('添加失败');
            }
        } else {
            $admin_role_db = D('Usap/Admin/Role');
            $rolelist = $admin_role_db->where(array('disabled' => '0'))->order('listorder asc')->getField('roleid,rolename', true);
            if (!empty($rolelist)) {

                foreach ($rolelist as $key => $val) if (strpos($val, '投注站') !== false) unset($rolelist[$key]);
            }
            $this->assign('rolelist', $rolelist);
            $this->display('member_add');
        }
    }

    /**
     * 编辑用户
     */
    public function memberEdit($id)
    {
        $admin_db = D('Usap/Admin/Admin');
        $user_db = D("Usap/Account/user");
        if (IS_POST) {
            if ($id == '1') $this->error('该用户不能被修改');
            $admin_info = $admin_db->where(['userid' => $id])->find();
            $data = I('post.info');
//            if ($data['roleid'] == 2) {
                $user_service = Service::instance()->find('account', 'user');
                $timestamp = time();
                $password = $user_service->genPasswd(md5($data['password']), $timestamp);
                $user_id = $admin_info['relationuid'];
                $user_data = array(
                    'user_password' => $password,
                    'status' => 'Active',//默认注册未激活
                    'real_name' => $data['realname'],
                    'mobile' => $data['mobile'],
                    'reg_time' => date('Y-m-d H:i:s', $timestamp),
                    'terminal_id' => 0,//设备类型ID
                );
                $user_db->where(['user_id' => $user_id])->save($user_data);
                $passwordinfo = password($data['password']);
                $data['password'] = $passwordinfo['password'];
                $data['encrypt'] = $passwordinfo['encrypt'];
                $result = $admin_db->where(array('userid' => $id))->save($data);
//            } else {
//                $passwordinfo = password($data['password']);
//                $data['password'] = $passwordinfo['password'];
//                $data['encrypt'] = $passwordinfo['encrypt'];
//                $result = $admin_db->where(array('userid' => $id))->save($data);
//            }
            if ($result) {
                $this->success('修改成功');
            } else {
                $this->error('修改失败');
            }
        } else {
            $admin_role_db = D('Usap/Admin/Role');
            $info = $admin_db->getUserInfo($id);
            $rolelist = $admin_role_db->where(array('disabled' => '0'))->order('listorder asc')->getField('roleid,rolename', true);
            $this->assign('info', $info);
            $this->assign('rolelist', $rolelist);
            $this->display('member_edit');
        }
    }

    /**
     * 重置用户密码
     */
    public function memberResetPassword($id)
    {

        $admin_db = D('Usap/Admin/Admin');
        $admin_re = $admin_db->where(array('userid' => $id))->field('mobile,encrypt,password')->find();
        if (empty($admin_re['mobile'])) {
            $this->error('手机为空,无法初始化密码');
            exit();
        }
        $password = substr($admin_re['mobile'], -6);
        $info = password($password, $admin_re['encrypt']);
        if ($info == $admin_re['password']) {
            $this->error('密码已被初始化,无法再初始化');
            exit();
        }
        $data = array(
            'password' => $info,
            'is_modified' => 1,
        );
        $result = $admin_db->where(array('userid' => $id))->save($data);
        $user_db = D("Usap/Account/user");
        $user_service = Service::instance()->find('account', 'user');
        $timestamp = time();
        $upassword = $user_service->genPasswd(md5($password), $timestamp);
        $user_id = $admin_re['relationuid'];
        $user_data = array(
            'user_password' => $upassword,
            'status' => 'Active',//默认注册激活
            'real_name' => $admin_re['realname'],
            'mobile' => $admin_re['mobile'],
            'reg_time' => date('Y-m-d H:i:s', $timestamp),
            'terminal_id' => 0,//设备类型ID
        );
        $user_db->where(['user_id' => $user_id])->save($user_data);
        if ($result) {
            $this->success("密码已重置为：" . $password . "，请牢记新密码！");
// 			$this->ajaxReturn(array('status'=>1, 'info'=>'初始化成功', 'password'=>$password));
        } else {
            $this->error('初始化失败');
        }
    }

    /**
     * 删除用户
     */
    public function memberDelete($id)
    {
        if ($id == '1') $this->error('该用户不能被删除');
        $admin_db = D('Usap/Admin/Admin');


        //查询结果
        $array = $admin_db->where("userid=$id")->find();
        if (empty($array)) {
            $this->error('用户不存在，无法删除');
            exit();
        }
        if (!empty($array['relationuid'])) {
            $this->error('投注店店长不能删除');
            exit();
        }
        $result = $admin_db->where(array('userid' => $id))->delete();
        if ($result) {
            $this->success('删除成功');
        } else {
            $this->error('删除失败');
        }
    }


    /**
     * 角色管理
     */
    public function roleList($page = 1, $rows = 10, $sort = 'listorder', $order = 'asc')
    {
        if (IS_POST) {
            $admin_role_db = D('Usap/Admin/Role');
            $total = $admin_role_db->count();
            $order = $sort . ' ' . $order;
            $limit = ($page - 1) * $rows . "," . $rows;
            $list = $admin_role_db->field('*,roleid as id')->order($order)->limit($limit)->select();
            $plist = [];
            foreach ($list as $value) {
                $plist[$value['roleid']] = $value['rolename'];
            }
            foreach ($list as $k => $v) {
                if ($v['pid'] == 0) {
                    $v['pid'] = '顶级';
                } else {
                    $v['pid'] = $plist[$v['pid']];
                }
                $list[$k] = $v;
            }
            if (!$list) $list = array();
            $data = array('total' => $total, 'rows' => $list);
            $this->ajaxReturn($data);
        } else {
            $menu_db = D('Usap/Admin/Menu');
            $currentpos = $menu_db->currentPos(I('get.menuid'));  //栏目位置
            $datagrid = array(
                'options' => array(
                    'title' => $currentpos,
                    'url' => U('admin/Admin/roleList', array('grid' => 'datagrid')),
                    'toolbar' => 'adminRoleModule.toolbar',
                ),
                'fields' => array(
                    '排序' => array('field' => 'listorder', 'width' => 5, 'align' => 'center', 'formatter' => 'adminRoleModule.sort'),
                    'ID' => array('field' => 'roleid', 'width' => 5, 'align' => 'center', 'sortable' => true),
                    '角色名称' => array('field' => 'rolename', 'width' => 15, 'sortable' => true),
                    '角色层级' => array('field' => 'pid', 'width' => 15, 'sortable' => true),
                    '角色描述' => array('field' => 'description', 'width' => 25),
                    '状态' => array('field' => 'disabled', 'width' => 15, 'sortable' => true, 'formatter' => 'adminRoleModule.state'),
                    '管理操作' => array('field' => 'id', 'width' => 20, 'formatter' => 'adminRoleModule.operate'),
                )
            );
            $this->assign('datagrid', $datagrid);
            $this->display('role_list');
        }
    }

    /**
     * 添加角色
     */
    public function roleAdd()
    {
        if (IS_POST) {
            $admin_role_db = D('Usap/Admin/Role');
            $data = I('post.info');
            if ($admin_role_db->where(array('rolename' => $data['rolename']))->field('rolename')->find()) {
                $this->error('角色名称已存在');
            }
            $id = $admin_role_db->add($data);
            if ($id) {
                $this->success('添加成功');
            } else {
                $this->error('添加失败');
            }
        } else {
            $this->display('role_add');
        }
    }

    /**
     * 编辑角色
     */
    public function roleEdit($id)
    {
        $admin_role_db = D('Usap/Admin/Role');
        $admin_admin_db = D('Usap/Admin/Admin');
        if (IS_POST) {
            $data = I('post.info');

            $info = $admin_role_db->where(array('roleid' => $id))->find();
            if ($info['disabled'] == '0' && $info['disabled'] != $data['disabled']) {

                //校验当前角色有绑定的管理员
                $count = $admin_admin_db->where(array('roleid' => $id))->count();
                if ($count > 0) {

                    $this->error('修改失败：系统中有管理员所属该角色，不能禁用');
                }
            }

            $id = $admin_role_db->where(array('roleid' => $id))->save($data);
            if ($id) {
                $this->success('修改成功');
            } else {
                $this->error('修改失败');
            }
        } else {
            $info = $admin_role_db->where(array('roleid' => $id))->find();
            $this->assign('info', $info);
            $this->display('role_edit');
        }
    }

    /**
     * 删除角色
     */
    public function roleDelete($id)
    {
        if ($id == '1') $this->error('该角色不能被删除');
        $admin_role_db = D('Usap/Admin/Role');

        $admin_admin_db = D("Usap/Admin/Admin");
        $count = $admin_admin_db->where(array('roleid' => $id))->count();
        if ($count > 0) {

            //校验当前角色有绑定的管理员
            $this->error('删除失败：系统中有管理员所属于该角色，不能删除');
        }

        $result = $admin_role_db->where(array('roleid' => $id))->delete();

        if ($result) {
            $this->success('删除成功');
        } else {
            $this->error('删除失败');
        }
    }

    /**
     * 角色排序
     */
    public function roleOrder()
    {
        if (IS_POST) {
            $admin_role_db = D('Usap/Admin/Role');
            foreach (I('post.order') as $roleid => $listorder) {
                $admin_role_db->where(array('roleid' => $roleid))->save(array('listorder' => $listorder));
            }
            $this->success('操作成功');
        } else {
            $this->error('操作失败');
        }
    }

    /**
     * 权限设置
     */
    public function rolePermission($id)
    {
        if (IS_POST) {
            $menu_db = D('Usap/Admin/Menu');
            if (I('get.dosubmit')) {
                $admin_role_priv_db = D("Usap/Admin/RolePriv");;
                $admin_role_priv_db->where(array('roleid' => $id))->delete();
                $menuids = explode(',', I('post.menuids'));
                $menuids = array_unique($menuids);
                if (!empty($menuids)) {
                    $menuList = array();
                    $menuinfo = $menu_db->field(array('id', 'c', 'a'))->select();
                    foreach ($menuinfo as $v) $menuList[$v['id']] = $v;
                    foreach ($menuids as $menuid) {
                        $info = array(
                            'roleid' => $id,
                            'c' => $menuList[$menuid]['c'],
                            'a' => $menuList[$menuid]['a'],
                        );
                        $admin_role_priv_db->add($info);
                    }
                }
                $this->success('权限设置成功');
                //获取列表数据
            } else {
                $data = $menu_db->getRoleTree(0, $id);
                $this->ajaxReturn($data);
            }
        } else {
            $this->assign('id', $id);
            $this->display('role_permission');
        }
    }

    /**
     * 栏目权限
     */
    public function roleCategory($id)
    {
        if (IS_POST) {
            $category_priv_db = D('Usap/Admin/CategoryPriv');
            if (I('get.dosubmit')) {
                $data = I('post.info');
                $category_priv_db->where(array('roleid' => $id))->delete();
                foreach ($data as $catid => $actionList) {
                    foreach ($actionList as $action) {
                        $category_priv_db->add(array(
                            'catid' => $catid,
                            'roleid' => $id,
                            'is_admin' => 1,
                            'action' => $action,
                        ));
                    }
                }
                $this->success('权限设置成功');
            } else {
                $data = $category_priv_db->getTreeGrid($id);
                $this->ajaxReturn($data);
            }
        } else {
            $treegrid = array(
                'options' => array(
                    'url' => U('admin/Admin/roleCategory', array('id' => $id, 'grid' => 'treegrid')),
                    'idField' => 'catid',
                    'treeField' => 'catname',
                ),
                'fields' => array(
                    '全选/取消' => array('field' => 'operateid', 'width' => 30, 'align' => 'center', 'formatter' => 'adminRoleModule.checkbox'),
                    '栏目ID' => array('field' => 'catid', 'width' => 20, 'align' => 'center'),
                    '栏目名称' => array('field' => 'catname', 'width' => 120),
                    '查看' => array('field' => 'field_view', 'width' => 15, 'align' => 'center', 'formatter' => 'adminRoleModule.field'),
                    '添加' => array('field' => 'field_add', 'width' => 15, 'align' => 'center', 'formatter' => 'adminRoleModule.field'),
                    '编辑' => array('field' => 'field_edit', 'width' => 15, 'align' => 'center', 'formatter' => 'adminRoleModule.field'),
                    '删除' => array('field' => 'field_delete', 'width' => 15, 'align' => 'center', 'formatter' => 'adminRoleModule.field'),
                    '审核' => array('field' => 'field_audit', 'width' => 15, 'align' => 'center', 'formatter' => 'adminRoleModule.field'),
                )
            );
            $this->assign('id', $id);
            $this->assign('treegrid', $treegrid);
            $this->display('role_category');
        }
    }

    /**
     * 验证邮箱是否存在
     */
    public function public_checkEmail($email = 0)
    {

        if (I('get.default') == $email) {
            exit('true');
        }

        $uid = I('get.uid');
        $admin_db = D('Usap/Admin/Admin');
        $exists = $admin_db->where("email='$email' AND userid!='$uid'")->field('email')->find();
        if ($exists) {
            exit('false');
        } else {
            exit('true');
        }
    }

    /**
     * 验证手机号是否存在
     */
    public function public_checkMobile($mobile = 0)
    {

        $uid = I('get.uid');
        if (I('get.default') == $mobile) {
            exit('true');
        }
        $admin_db = D('Usap/Admin/Admin');
        $exists = $admin_db->where("mobile='$mobile' AND userid!='$uid'")->field('mobile')->find();
        if ($exists) {
            exit('false');
        } else {
            exit('true');
        }
    }

    /**
     * 验证密码
     */
    public function public_checkPassword($password = 0)
    {
        $userid = session('userid');
        $admin_db = D('Usap/Admin/Admin');

        $verify_result = $admin_db->verifyPassword($userid, $password);

        if (!$verify_result) {
            exit('false');
        } else {
            exit('true');
        }
    }

    /**
     * 验证用户名
     */
    public function public_checkName($name)
    {
        if (I('get.default') == $name) {
            exit('true');
        }

        if (preg_match('/^1[0-9]{10}$/', $name)) {
            exit('false');
        }


        $admin_db = D('Usap/Admin/Admin');
        $exists = $admin_db->where(array('username' => $name))->field('username')->find();
        if ($exists) {
            exit('false');
        } else {
            exit('true');
        }
    }

    /**
     * 验证角色名称是否存在
     */
    public function public_checkRoleName($rolename)
    {
        if (I('get.default') == $rolename) {
            exit('true');
        }
        $admin_role_db = D('Usap/Admin/Role');
        $exists = $admin_role_db->where(array('rolename' => $rolename))->field('rolename')->find();
        if ($exists) {
            exit('false');
        } else {
            exit('true');
        }
    }
}
